package com.mune.gulimall.cart.interceptor;

import com.mune.common.constant.AuthServerConstant;
import com.mune.common.constant.CartConstant;
import com.mune.common.constant.GlobalConstant;
import com.mune.common.to.MemberSessionTo;
import com.mune.gulimall.cart.to.UserInfoTo;
import jdk.nashorn.internal.objects.Global;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class LoginUserInterceptor implements HandlerInterceptor {

  public static ThreadLocal<UserInfoTo> toThreadLocal = new ThreadLocal<>();

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    UserInfoTo userInfoTo = new UserInfoTo();
    HttpSession session = request.getSession();
    MemberSessionTo memberSessionTo = (MemberSessionTo) session.getAttribute(AuthServerConstant.LOGIN_USER);
    if (memberSessionTo != null) {
      userInfoTo.setUserId(memberSessionTo.getId());
    }
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
      for (Cookie cookie : cookies) {
        String name = cookie.getName();
        if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
          userInfoTo.setUserKey(cookie.getValue());
          userInfoTo.setHasUserKey(true);
          break;
        }
      }
    }
    if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
      String uuid = UUID.randomUUID().toString();
      userInfoTo.setUserKey(uuid);
    }
    toThreadLocal.set(userInfoTo);
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    UserInfoTo userInfoTo = toThreadLocal.get();
    if (!userInfoTo.getHasUserKey()) {
      Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
      cookie.setDomain(GlobalConstant.SESSION_DOMAIN_NAME);
      cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
      response.addCookie(cookie);
    }
  }
}
